package dsl.client;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.Socket;

public class App {
    private static final Integer END = 0;
    private static final Integer NEED_INPUT = 2;

    /**
     * 通过{@link dsl.client.GUI}以对话框方式告知用户错误
     * 接入服务器后，与智能客服进行交流，是否能发送信息由服务器要求而定
     * 
     * @param args
     */
    public static void main(String[] args) {
        String host = "127.0.0.1";
        int port = 8000;
        try {
            int key = 0;
            String str = "";
            StringBuilder stringBuilder = new StringBuilder();
            Socket client = new Socket(host, port);
            BufferedReader input = new BufferedReader(new InputStreamReader(client.getInputStream(), "UTF-8"));
            DataOutputStream output = new DataOutputStream(client.getOutputStream());
            DialogBox dialogBox = new DialogBox();
            MyLogger.logger.info("Connected to the server");

            // 与服务端交谈，当服务器要求退出时退出
            while (true) {
                receiveMessage(input, stringBuilder);
                key = stringBuilder.charAt(0) - '0';
                stringBuilder.deleteCharAt(0);
                if (!stringBuilder.toString().equals(""))
                    dialogBox.printInfo(stringBuilder.toString(), DialogBox.CUSTOM_SERVICE_ID);
                if (key == NEED_INPUT) {
                    while (dialogBox.str.equals(""))
                        Thread.sleep(100);
                    str = dialogBox.str;
                    dialogBox.str = "";
                    dialogBox.printInfo(str, DialogBox.CUSTOM_ID);
                    sendMessage(output, str);
                } else if (key == END) {
                    break;
                }
            }

            // 交流结束后10s关闭对话框
            output.close();
            input.close();
            client.close();
            dialogBox.printInfo("end", DialogBox.SYSTEM_ID);
            Thread.sleep(10000);
            dialogBox.close();
            MyLogger.logger.info("结束");
        } catch (Exception e) {
            GUI.showInfo("Sorry! error!");
            MyLogger.logger.warning("error");
        }
    }

    /**
     * 接受服务器发送的信息
     * 
     * @param input         输入流
     * @param stringBuilder 存储接受的信息
     * @throws IOException
     */
    private static void receiveMessage(BufferedReader input, StringBuilder stringBuilder)
            throws IOException, InterruptedException {
        String str = null;
        stringBuilder.delete(0, stringBuilder.length());
        while ((str = input.readLine()) == null)
            ;
        stringBuilder.delete(0, stringBuilder.length());
        stringBuilder.append(str);
    }

    /**
     * 向服务器发送信息
     * 
     * @param output  输出流
     * @param message 要输出的信息
     * @throws UnsupportedEncodingException
     * @throws IOException
     */
    private static void sendMessage(DataOutputStream output, String message)
            throws UnsupportedEncodingException, IOException {
        output.flush();
        output.write((message + "\n").getBytes("UTF-8"));
    }
}
